package org.atf.model.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.atf.model.entity.Jobs;
import org.atf.model.entity.Preference;
import org.atf.model.entity.Profile;
import org.atf.model.entity.Server;
import org.atf.model.utils.EntityManagerUtil;


public class ProfileDAO {
	
	
	public List<Profile> getProfiles(){	
		EntityManager entityManager=EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p from Profile p");
		List<Profile> resultList = query.getResultList();
		return resultList;
	}
	
	public void deleteProfile(int id){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		 try{
			    Profile profile=entityManager.find(Profile.class, id);
				entityManager.getTransaction().begin();
				
				entityManager.remove(profile);
				entityManager.getTransaction().commit();
		 } finally {
		//	 entityManager.close();
		 }	
	}
	public void updateProfile(Profile profile){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			entityManager.merge(profile);
			entityManager.getTransaction().commit();
		}finally {
		//	entityManager.close();
		}
		
	}
	public void insertProfile(Profile profile){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			entityManager.persist(profile);
			entityManager.getTransaction().commit();
		}finally {
		//	entityManager.close();
		}
	}
	public Profile getProfile(Integer id){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Profile profile;
		 try{
				entityManager.getTransaction().begin();
				profile=entityManager.find(Profile.class, id);
				entityManager.getTransaction().commit();
		 } finally {
		//	 entityManager.close();
		 }	
		 return profile;
	}
	public List<Preference> getPreference(Integer profileId){
	//	EntityManager entityManager = EntityManagerUtil.getEntityManager();
		List<Preference> prefList = new ArrayList<Preference>();
		try{
//			prefList =
//					entityManager.createNamedQuery("Profile.findAllPreference")
//					.setParameter("profileId", profileId)
//					.getResultList();
			prefList.addAll(getProfile(profileId).getPreference());
			System.out.println(prefList);
		}finally {
		//	entityManager.close();
		}
		return prefList;
	}
	public List<Server> getServers(Integer profileId){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		List<Server> serverList = new ArrayList<Server>();
		try{
//			serverList =
//					entityManager.createNamedQuery("Profile.findAllServer")
//					.setParameter("profileId", profileId)
//					.getResultList();
			serverList.addAll(getProfile(profileId).getServers());
		}finally {
		//	entityManager.close();
		}
		return serverList;
	}
	
	public Server addServerToProfile(Integer profileId, Server server ){
		
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		 try{
			 entityManager.getTransaction().begin();
			 entityManager.persist(server);
			 Profile profile=entityManager.find(Profile.class, profileId);
			 profile.addServer(server);
			 entityManager.merge(profile);
			 entityManager.getTransaction().commit();
	 
		 }finally {
		//	 entityManager.close();
		 }	
		return server;
	}
	public void deletePreference(Integer profileId, Integer prefId) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		
		 try{
				entityManager.getTransaction().begin();
				Profile profile=entityManager.find(Profile.class, profileId);
				Preference pref = null;
				for(Preference preference : profile.getPreference()) {
					if(preference.getId() == prefId){
						pref= preference;
						//entityManager.remove(preference);
					}
				}
				if(pref != null){
					profile.removePreference(pref);
				}
				entityManager.remove(pref);
				entityManager.merge(profile);
				entityManager.getTransaction().commit();
				
				
		 } finally {
			// entityManager.close();
		 }	
	}
	public void insertPreference(Integer profileId, Preference preference) {
		// TODO Auto-generated method stub
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		 try{
			 entityManager.getTransaction().begin();
			 entityManager.persist(preference);
			 System.out.println("Persist: "+preference);
			 Profile profile=entityManager.find(Profile.class, profileId);
			 profile.addPreference(preference);
			 entityManager.merge(profile);
			 entityManager.getTransaction().commit();
			 
			 
		 }finally {
			// entityManager.close();
		 }	
		
	}
	
	public Server isServerExists(Integer profileId, Server server) throws NoResultException{
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createNativeQuery("select S.* from PROFILE_SERVER PS,SERVER S "
				+ "WHERE PS.PROFILE_ID= "+profileId
						+ " AND PS.SERVER_ID  = S.SERVER_ID "
						+ " AND S.SERVERNAME='"+server.getServername()+"'"
						+ " AND S.HOSTNAME='"+server.getHostname()+"'"
						+ " AND S.NODENAME='"+server.getNodename()+"'", Server.class);
		Server result = null;
		try {
			result = (Server) query.getSingleResult();
		}catch(NoResultException e){
			
		}
		return result;
		
	}
	
	public Integer getProfileIdByServerId(Integer serverId){
		
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createNativeQuery("select PS.PROFILE_ID from PROFILE_SERVER PS WHERE PS.SERVER_ID="+serverId);
	//	query.setParameter("serverId",serverId);
		Integer result;
		try {
			result = (Integer) query.getSingleResult();
		}catch(NoResultException e){
			result = -1;
		}

		return result;
		
	}
	
	public String getProfileName(Integer profileId){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p.profileName from Profile p where p.id = :id");
		query.setParameter("id",profileId);
		String profileName= "";
		try {
			profileName = (String) query.getSingleResult();
		}catch(NoResultException e){
			
		}
		return profileName;
		
	}
	public String getProfileRegion(Integer profileId){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p.region from Profile p where p.id = :id");
		query.setParameter("id",profileId);
		String region= "";
		try {
			region = (String) query.getSingleResult();
		}catch(NoResultException e){
			
		}
		return region;
		
	}
	public String getProfileHostname(Integer profileId){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p.hostname from Profile p where p.id = :id");
		query.setParameter("id",profileId);
		String hostname= "";
		try {
			hostname = (String) query.getSingleResult();
		}catch(NoResultException e){
			
		}
		return hostname;
		
	}
	 

	public void addOrUpdateServers(Integer profileId, List<Server> serverList) {
		System.out.println(serverList);
		// TODO Auto-generated method stub
		ServerDAO serverDAO = new ServerDAO();
		for(Server server: serverList){
			
				Server oServer= isServerExists(profileId, server);
				if( oServer == null){
					//serverDAO.insertServer(server);
					addServerToProfile(profileId, server);
				}else{
					System.out.println("oServer"+oServer);
					//server.setId(oServer.getId());
					oServer.updateProperties(oServer);
					serverDAO.mergeServer(oServer);
				}

		}
	}
	public List<String> getProfileUniqueRegions() {
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select distinct p.region from Profile p");
		List<String> resultList = query.getResultList();
		return resultList;
	}
	public List<Profile> getProfilesByType(String type){	
		EntityManager entityManager=EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p from Profile p where p.profileType='"+type+"'");
		List<Profile> resultList = query.getResultList();
		return resultList;
	}
	public List<Profile> getProfileByTypeRegion(String profileType, String region) {
		EntityManager entityManager=EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p from Profile p where p.profileType='"+profileType+"' and p.region='"+region+"'");
		List<Profile> resultList = query.getResultList();
		return resultList;
	}
	
	public Profile getProfileByRegionName(String region, String profileName) {
		EntityManager entityManager=EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select p from Profile p where p.region='"+region+"' and p.profileName='"+profileName+"'");
		List<Profile> resultList = query.getResultList();
		if(resultList.size() > 0){
			return resultList.get(0);
		}
		return null;
	}
	
	public void updateWebProfile(Profile profile){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		entityManager.getTransaction().begin();
		
		Profile cProfile=entityManager.find(Profile.class, profile.getId());	
		cProfile.updateProperties(profile);	
		entityManager.merge(cProfile);
		entityManager.getTransaction().commit();
		
	}


	
}
